<?php
namespace Admin\Controller;
use Think\Controller;
class CategoryController extends CommonController {
    //分类列表
    public function index(){
        $model = M('Category');
        $tree = $model->order('sort asc')->select();
        $tree = get_category_list($tree,'|---');
        $this->assign('list',$tree);
        $this->display();
    }

    //添加分类
    public function add(){
        if (IS_POST) {
            $data = I('post.');
            $model = D('Category');
            $rs = $model->create();
            if (!$rs) {
                $this->error($model->getError());
            }else{
                $rs = $model->add();
                if (!$rs) {
                    $this->error('添加失败');
                }else{
                    $this->success('添加成功');
                }
            }

        }else{
            $model = M('Category');
            $data = $model ->select();
            $top = array(
                array(
                        'id'=>0,
                        'pid' =>'0',
                        'name' =>"顶级分类"
                    )
                );
            $data = array_merge($top,$data);
            $this->assign('category',$data);
            $this->display();
        }
    }
    //修改分类
    public function edit(){
        if (IS_POST) {
            $data = I('post.');
            $model = D('Category');
            $check = $model->checkCategory($data);
            if (!$check) {
                $this->error('不能将本栏目添加到自己的子分类');
            }
            $rs = $model->create();
            if (!$rs) {
                $this->error($model->getError());
            }else{
                $rs = $model->save();
                if (!$rs) {
                    $this->error('修改失败');
                }else{
                    $this->success('修改成功');
                }
            }
        }else{
            $model = M('Category');
            $map['id'] = I('get.id');
            $data = $model->where($map)->find();
            $category = $model->select();
            $pid_name = $model->where(array('id'=>$data['pid']))->getField('name');
            $this->assign('data',$data);
            $this->assign('category',$category);
            $this->assign('pid_name',$pid_name);
            $this->display();
        }

    }
    //删除分类
    public function del($id=null){
        if($id==""||!is_numeric($id)){
            $this->error('ID错误!');
        }else{
            $model = M('Category');
            $rs = $model->delete($id);
            if (!$rs) {
                $this->error('删除失败!');
            }else{
                $this->success('删除成功!');
            }
        }
        $this->display();
    }
}